﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using BaocaoNPC.common;
using Component;
using CMISLibrary;
//using busBaoCao;
using CMISLibrary.Libraries;
using System.IO;
using Microsoft.VisualBasic;
using BaocaoNPC.Usercontrols.reports;
namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for InDsKhachHang.xaml
    /// </summary>
    public partial class InDsKhachHang : UserControl
    {
        #region Khai báo biến
        public String strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strTenDNHap = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public String strMa_TNgan = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap.ToUpper() : "PA";
        DataSet ds_BBTHUNGAN = new DataSet();
        DataSet ds_HOADONTNGAN = new DataSet();
        DataSet dsResult = new DataSet();
        DataTable dtResult = new DataTable();
        int dkien = 0;
        string maloi;
        #endregion
        public InDsKhachHang()
        {
            InitializeComponent();
            LOAD_DATA();
        }
        private void LOAD_DATA()
        {
            try
            {
                dkien = 0;
                ds_BBTHUNGAN = new DataSet();
                ds_HOADONTNGAN = new DataSet();
                //ds_BBTHUNGAN = cls.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 0, ref maloi);
                ds_BBTHUNGAN = GlobalServices.Service_NPCUS.SELECT_CN_BBAN_TNGAN(strMa_dviqly, strMa_TNgan, 0, ref maloi);
                ds_HOADONTNGAN = GlobalServices.Service_NPCUS.SELECT_CN_HOADON_TNGAN(strMa_dviqly, strMa_TNgan, 0, "", "ALL", dkien, ref maloi);
                if (ds_HOADONTNGAN.Tables != null)
                {
                    dtResult = ds_HOADONTNGAN.Tables[0].Clone();
                    dsResult.Tables.Add(dtResult);
                }
                fill_dulieu(ds_BBTHUNGAN);
                
            }
            catch
            { }
        }
        private void fill_dulieu(DataSet ds)// hàm này đưa dữ liệu từ đầu vào dataset();
        {
            try
            {
                if (ds.Tables.Count == 0) return;
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();
                CheckBox chkSuperNode = new CheckBox();
                // filter_treeDataSet();
                this.trvBBAN.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                DataView dv = new DataView(ds.Tables[0]);
                dv.Sort = "MA_SOGCS";
                if (dv.Count == 0) // không có dữ liệu không đưa ra tree
                {
                    superNode.Header = "Không có dữ liệu biên bản";
                    superNode.Tag = "Không có dữ liệu biên bản@";
                    trvBBAN.Items.Add(superNode);
                    return;
                }
                chkSuperNode = new CheckBox();
                chkSuperNode.Content = "Tất cả sổ GCS";
                chkSuperNode.Tag = "@NUTGOC";
                chkSuperNode.ToolTip = "Biên bản";
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                //superNode.IsSelected = true;
                trvBBAN.Items.Add(superNode);
                string strnutcha = "";
                string strnutcon = "";
                string str_bienban = "";
                string str_ma_sogcs = "";
                string str_ma_dviqly = "";
                foreach (DataRowView dr in dv)
                {
                    str_ma_dviqly = dr["MA_DVIQLY"].ToString();
                    str_ma_sogcs = dr["MA_SOGCS"].ToString();
                    
                    #region "parentnode"
                    if (str_ma_sogcs != strnutcha)
                    {
                        chkNode = new CheckBox();
                        chkNode.Content = str_ma_sogcs;// +" -" + dr["NGAY_GIAO"].ToString();
                        chkNode.Tag = str_ma_sogcs + "@NUTCHA";
                        chkNode.ToolTip = str_ma_sogcs;
                        chkNode.IsChecked = false;
                        chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _node = new TreeViewItem();
                        _node.Header = chkNode;
                        _node.IsExpanded = true;
                        superNode.Items.Add(_node);
                        strnutcha = str_ma_sogcs;
                    }
                    # endregion
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
        public void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                //chk.Cursor = Cursors.Wait;
                //lblstatus.Content = "Đang lấy dữ liệu hóa đơn...";
                TreeViewItem itemselect = trvBBAN.SelectedItem as TreeViewItem;
                string soBBanPbo = "", ngayPbo = "";
                //get_chkItem(chk, ref soBBanPbo, ref ngayPbo);
                //dt = new DataTable();
                //dt = this.dsResult.Tables["CTO"].Clone();
                // cắt mảng tag
                string[] m = chk.Tag.ToString().Split('@');
                if (chk.IsChecked == true)
                {
                    //kiem tra xem root or leaf duoc check
                    //#region Check All ChildNode
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        checkList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    // nếu click nút tổng
                    if (chk.Tag.ToString() == "@NUTGOC")
                    {
                        dtResult.Rows.Clear();
                        dtResult = ds_HOADONTNGAN.Tables[0].Copy();
                    }

                    // nếu clich nút cha
                    if (m[1].ToString() == "NUTCHA")
                    {
                        DataTable dt = ds_HOADONTNGAN.Tables[0].Select("MA_SOGCS = '" + m[0].ToString() + "'").CopyToDataTable();
                        copy_dataTable(dt, dtResult);
                    }
                }
                else
                {
                    //DataRow dr =null;
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        UncheckList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (chk.Tag.ToString() == "@NUTGOC")
                    {
                        dtResult.Rows.Clear();
                    }
                    // nếu clich nút cha
                    if (m[1].ToString() == "NUTCHA")
                    {
                        for (int i = dtResult.Rows.Count - 1; i >= 0; i--)
                        {
                            if (dtResult.Rows[i]["MA_SOGCS"].ToString() == m[0].ToString())
                            {
                                dtResult.Rows[i].Delete();
                            }
                        }
                        dtResult.AcceptChanges();
                    }
                }
                //
            }
            catch
            {
                this.Cursor = Cursors.Arrow;
                return;

            }
            this.Cursor = Cursors.Arrow;
        }
        private void copy_dataTable(DataTable dtnguon, DataTable dtDich)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    dr["CHON"] = rgINS[i]["CHON"].ToString();
                    dr["STT"] = rgINS[i]["STT"].ToString();
                    dr["KYTHANGNAM"] = rgINS[i]["KYTHANGNAM"].ToString();
                    dr["MA_DVIQLY"] = rgINS[i]["MA_DVIQLY"].ToString();
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"].ToString();
                    dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"].ToString();
                    dr["DCHI_KHANG"] = rgINS[i]["DCHI_KHANG"].ToString();
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"].ToString();
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"].ToString();
                    //string a = Convert.ToDecimal(rgINS[i]["TONGTIEN"]).ToString("# ### ### ###");
                    dr["TONGTIEN"] = rgINS[i]["TONGTIEN"];
                    //string b = "";
                    //if (rgINS[i]["TONGNOP"].ToString() != "") b = Convert.ToDecimal(rgINS[i]["TONGNOP"]).ToString("# ### ### ###");
                    dr["TONGNOP"] = rgINS[i]["TONGNOP"];
                    dr["TIEN_NO"] = rgINS[i]["TIEN_NO"];
                    dr["THUE_NO"] = rgINS[i]["THUE_NO"];
                    dr["SO_SERY"] = rgINS[i]["SO_SERY"];
                    dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["NGAY_GIAO"] = rgINS[i]["NGAY_GIAO"];
                    dr["TRANGTHAI"] = rgINS[i]["TRANGTHAI"];
                    dr["MA_TRAM"] = rgINS[i]["MA_TRAM"];
                    dr["SO_COT"] = rgINS[i]["SO_COT"];
                    dr["SO_HOM"] = rgINS[i]["SO_HOM"];
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                    //ds_HDONCHAMNO.AcceptChanges();
                }
            }
            catch
            { }
        }
        private void UncheckList(TreeViewItem nodes, CheckBox chk)
        {
            //dt.Rows.Clear();
            if ((CheckBox)nodes.Header == chk)
            {
                UnCheckAllChildsWhenParentUnCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    UnCheckParent(node);
                    if (node.Items.Count > 0)
                    {
                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = false;
                            if (subNode.Items.Count > 0)
                            {
                                UncheckList(subNode, chk);
                            }
                            //load database of childnode
                            //KiemTra_Insert_tbl_All_TheoDoiNo(chkChildNode);
                        }
                    }
                    else
                    {
                        CheckBox chkNode = (CheckBox)node.Header;
                        chkNode.IsChecked = false;
                    }
                }
                else
                {
                    UncheckList(node, chk);
                }

            }
        }
        private void UnCheckParent(TreeViewItem node)
        {
            TreeViewItem parentNode = node.Parent as TreeViewItem;
            if (parentNode != null)
            {
                CheckBox chkParentNode = (CheckBox)parentNode.Header;
                chkParentNode.IsChecked = false;
                UnCheckParent(parentNode);
            }
        }
        private void RefreshCheckBoxList(TreeViewItem nodes)
        {
            DataRow[] dr = null;
            foreach (TreeViewItem subNode in nodes.Items)
            {
                //check all Node
                CheckBox chkNode = (CheckBox)subNode.Header;
                if (subNode.Items.Count > 0)
                {
                    RefreshCheckBoxList(subNode);
                }
                else
                {
                    if (chkNode.IsChecked == true)
                    {
                        //if (tabTimKiem1.SelectedIndex == 0)
                        //{
                        //    if (cboTTrangCTo.SelectedIndex == 0)
                        //        dr = this.dsResult.Tables["CTO"].Select("SO_BBAN = '" + chkNode.Content.ToString() + "'");
                        //    else
                        //        //dr = this.dsResult.Tables["CTO"].Select("SO_BBAN = '" + chkNode.Content.ToString() + "'");

                        //        dr = this.dsResult.Tables["CTO"].Select("SO_BBAN_KDINH = '" + chkNode.Content.ToString() + "'");
                        //}
                        //else
                        //{
                        //    dr = this.dsResult.Tables["CTO"].Select("ID_BBAN_PBO = " + chkNode.Content.ToString() + "");
                        //    // lay thong tin ID phan bo
                        //    DataRow drBB = dsSearh.Tables["DD_BBAN_PBO"].NewRow();
                        //    drBB["MA_DVIQLY"] = strMaDViQLy;
                        //    drBB["ID_BBAN_PBO"] = Convert.ToInt64(chkNode.Content.ToString());
                        //    drBB["MA_DVIQLY_NHAN"] = dr[0]["MA_DVIQLY_NHAN"].ToString();
                        //    dsSearh.Tables["DD_BBAN_PBO"].Rows.Add(drBB);
                        //    dsSearh.AcceptChanges();
                        //}
                        //foreach (DataRow dro in dr)
                        //{
                        //    dt.ImportRow(dro);
                        //}
                    }
                    else
                    {
                        //if (tabTimKiem1.SelectedIndex == 1)
                        //{
                        //    //DataRow[] drDelete = null;
                        //    DataRow drDelete = dsSearh.Tables["DD_BBAN_PBO"].Select("ID_BBAN_PBO = " + chkNode.Content.ToString() + "").FirstOrDefault();
                        //    if (drDelete != null)
                        //    {
                        //        drDelete.Delete();
                        //    }
                        //    dsSearh.AcceptChanges();
                        //}
                    }
                }
            }
        }
        private void checkList(TreeViewItem nodes, CheckBox chk)
        {

            if ((CheckBox)nodes.Header == chk)
            {
                CheckAllChildsWhenParentCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    if (node.Items.Count > 0)
                    {

                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = true;
                            if (subNode.Items.Count > 0)
                            {
                                checkList(subNode, chk);
                            }
                        }
                        CheckParentWhenAllChildChecked(nodes);
                    }
                    else
                    {

                        CheckParentWhenAllChildChecked(nodes);
                    }
                }
                else
                {
                    checkList(node, chk);
                }

            }
        }
        private void CheckParentWhenAllChildChecked(TreeViewItem nodes)
        {
            int count = 0;
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                if (chkNode.IsChecked == false)
                {
                    count = count + 1;
                    break;
                }
            }
            if (count == 0)
            {
                CheckBox chkNode = (CheckBox)nodes.Header;
                chkNode.IsChecked = true;
                TreeViewItem parentNode = nodes.Parent as TreeViewItem;
                if (parentNode != null)
                {

                    CheckParentWhenAllChildChecked(parentNode);
                }
            }
        }

        private void CheckAllChildsWhenParentCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = true;
                CheckAllChildsWhenParentCheck(node);
            }
        }
        private void UnCheckAllChildsWhenParentUnCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = false;
                UnCheckAllChildsWhenParentUnCheck(node);
            }
        }

        private void btnIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dtResult.Rows.Count == 0)
                { MessageBox.Show("Không có dữ liệu theo điều kiện chọn"); return; }
                if (dtResult.Rows.Count > 0)
                {
                    rpt_NPC_INDSKHACHANGTIENDIEN rpt = new rpt_NPC_INDSKHACHANGTIENDIEN();
                    rpt.SetDataSource(dtResult);
                    //rpt.SetParameterValue("ptungay", ptungay);
                    //rpt.SetParameterValue("pdenngay", pdenngay);
                    //rpt.SetParameterValue("pTendienluc", strTen_dviqly);
                    //rpt.SetParameterValue("pTencongty", strTen_dviqly_CT);
                    //ds_chamnooffline.WriteXmlSchema("D:\\Projects\\DSCHAMNO.xsd");
                    UtilReportOMS.RptManager.showReportToWin(this, rpt, strMa_dviqly, new string[] { "Formula1", "Formula2", "Formula3" }, new string[] { "Formula1", "Formula2", "Formula3" }, "CMIS2 - Report: Báo cáo NPC");
                }
                else
                { MessageBox.Show("Không có dữ liệu theo điều kiện chọn"); return; }
            }
            catch
            { }
        }
    }
}
